<?php
namespace app\index\controller;

use think\Request;
use think\Db;
use app\index\model\RankModel;

class Rank extends BaseController
{
    public function get()
    {
        $tableName = request()->param('tableName');
        $rankCount = request()->param('rankCount');
        $maxScore = request()->param('maxScore');
        if($rankCount > 100)
        {
            $rankCount = 100;
        }
        if($rankCount <= 0)
    	{
    		return 'error_rank_count';
    	}
        if(empty($tableName))
        {
            return 'error_table_name';
        }
        if($tableName != 'rank_model')
        {
            return 'error_table_name';
        }
    	// load from db
        if(empty($maxScore))
        {
            $list = Db::table($tableName)
                ->limit($rankCount)
                ->order('score desc, update_time')
                ->select();  
        }
        else
        {
            $list = Db::table($tableName)
                ->where('score', 'elt', $maxScore)
                ->limit($rankCount)
                ->order('score desc', 'updateTime')
                ->select();            
        }


    	return json_encode($list);
    }

    public function save()
    {
        $playerId = request()->param('playerId');
        $data = request()->param('rankData');
        $score = request()->param('score');
        if(empty($playerId))
    	{
    		return 'error_player_id';
    	}
    	if(empty($data))
    	{
    		return 'error_rank_data';
    	}
        $rankData = RankModel::where('pid',$playerId)->find();
        if(empty($rankData))
        {
            //save data to db
            $rankData = RankModel::create([
                'pid'  =>  $playerId,
                'data' =>  $data,
                'update_time' => time(),
                'created' => time(),
                'score' => $score,
            ]);
        }
        else{
            //save data to db
            $rankData = RankModel::update([
                'data' =>  $data,
                'score' => $score,
                'update_time' => time(),
            ], ['pid' => $playerId]);
        }

    	return json_encode($rankData);
    }

}
